<template>
  <div>
    <input style="display: none" type="file" id="file" @change="fileChange" />
    <label for="file">
      <div style="text-align: center">请选择文件</div>
    </label>
    <div style="text-align: center; margin-top: 0.25rem" v-if="!disabled">
      {{ currentFile.name }}
    </div>
  </div>
  <div style="text-align: center; margin-top: 2rem">
    <button style="font-size: 1rem" :disabled="disabled" @click="importFile">
      导入文件
    </button>
  </div>
  <!-- 文件导出 -->
  <div style="text-align: center; margin-top: 2rem">
    <button style="font-size: 1rem" @click="outputFile">导出文件</button>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import { importData,outputData } from "../util/api";

export default defineComponent({
  setup() {
    let currentFile = ref(new Blob());
    let disabled = ref(true);

    function fileChange(e: Event) {
      console.log(e);
      console.log((e.target as HTMLInputElement).files);
      if ((e.target as HTMLInputElement).files?.length) {
        currentFile.value = ((e.target as HTMLInputElement)
          .files as FileList)[0];
        disabled.value = false;
      }
    }

    function importFile() {
      const fileReader = new FileReader();
      fileReader.onloadend = function (evt: ProgressEvent<FileReader>) {
        // 在文件读取完毕后，其内容将被保存在result属性中
        if (!evt.target) return;
        const content = evt.target.result;
        const contentObject = JSON.parse(content as string);
        importData(contentObject)
          .then((res) => {
            if (res.code === 0) {
              console.log("导入成功");
            }
          })
          .catch((e) => {
            console.log("导入错误", e);
          });
      };
      fileReader.readAsText(currentFile.value, "utf-8");
    }
    function outputFile() {
      outputData();
    }
    return { importFile, outputFile, fileChange, disabled, currentFile };
  },
});
</script>
<style lang="scss" scoped>
</style>
